'use client';

import { useClientParams } from '@/hooks';
import { staticGo } from '@/utils/common';
import { useEffect, useState } from 'react';
import './FilterTags.scss';

const FilterTags = () => {
  const { pathname, queryObject, filterObject } = useClientParams();
  const filterList = Object.values(filterObject).filter(
    e => e.datakey != 'q' && e.datakey != 'cat'
  );
  const [allFilters, setAllFilters] = useState(filterList);

  const handleRemoveTag = (e: any) => {
    const elm = e.currentTarget;
    if (elm?.dataset?.datakey) {
      const newQueryObject: Obj = { ...queryObject };
      delete newQueryObject[elm?.dataset?.datakey];
      staticGo(pathname, { ...newQueryObject });
    }
  };

  const handleClearFilter = () => {
    const newQueryObject: Obj = { ...queryObject };
    Object.values(filterObject)
      .filter(e => e.datakey != 'q' && e.datakey != 'cat')
      .forEach(e => {
        delete newQueryObject[e.datakey];
      });
    staticGo(pathname, { ...newQueryObject });
  };

  useEffect(() => {
    const filterList = Object.values(filterObject).filter(
      e => e.datakey != 'q' && e.datakey != 'cat'
    );
    setAllFilters(filterList);
  }, [filterObject]);

  return (
    <div className={`filter-tags ${allFilters?.length && 'have-content'}`}>
      {allFilters?.map((ft: any, index: number) => (
        <div key={index} className="filter-tags-tag">
          {ft.title}
          <span
            className="iconfont icon-close"
            data-datakey={ft.datakey}
            onClick={handleRemoveTag}
          ></span>
        </div>
      ))}
      {allFilters?.length > 0 && (
        <div className="filter-tags-clear">
          <span onClick={handleClearFilter}>Clear all</span>
        </div>
      )}
    </div>
  );
};

export default FilterTags;
